package com.aht.qywxwebdemo;

import cn.hutool.json.JSONUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

@RestController
public class QywxApi {
    @Autowired
    private WxCpService wxCpService;

    @GetMapping("/ldnh/qywxapi/home")
    public RedirectView redirectToAnotherUrl() {
        RedirectView redirectView = new RedirectView();
        String url = wxCpService.getOauth2Service().buildAuthorizationUrl("http://zhzhy.online:8383/ldnh/qywxapi/oauth2callback", "ldchina");
        redirectView.setUrl(url); // 设置重定向的URL
        return redirectView;
    }

    @GetMapping("/ldnh/qywxapi/oauth2callback")
    public WxCpUser oauth2Callback(@RequestParam("code") String code) throws WxErrorException {
        WxCpOauth2UserInfo wxCpOauth2UserInfo =  wxCpService.getOauth2Service().getUserInfo(code);
        System.out.println(wxCpOauth2UserInfo.getOpenId());
        System.out.println(wxCpOauth2UserInfo.getUserId());
        wxCpOauth2UserInfo.getUserTicket();
        WxCpUser wxCpUser = wxCpService.getUserService().getById(wxCpOauth2UserInfo.getUserId());
        System.out.println(JSONUtil.toJsonPrettyStr(wxCpUser));
        return  wxCpUser;
    }

    @GetMapping("/WW_verify_vL4vvX72oDr4toa7.txt")
    public String check() {
        return "vL4vvX72oDr4toa7";
    }

}
